/**
 * Copyright @ 2000 ysten Co. Ltd.
 * All right reserved.
 * @author: wangmin
 * date: 2016-05-13
 */

$(function () {
    var url;
    $('#productGrid').datagrid({
        url: 'findProductPage.json',
        singleSelect: true,
        fitColumns: true,
        rownumbers: true,
        pagination: true,
        pageSize: 20,
        shadow: false,
        columns: [
            [
                {title: '<b>编码</b>', field: 'id', align: 'center', width: 100, sort: 'clientSide'},
                {title: '<b>名称</b>', field: 'name', align: 'center', width: 150, sort: 'clientSide'},
                {title: '<b>价格</b>', field: 'price', align: 'center', width: 100, sort: 'clientSide'},
                {title: '<b>品牌</b>', field: 'brand', align: 'center', width: 150, sort: 'clientSide', formatter: function (value, row, index) {
                    if (row.brand) {
                        return row.brand.name;
                    } else {
                        return "";
                    }
                }},
                {title: '<b>分类</b>', field: 'twoLevelType', align: 'center', width: 150, sort: 'clientSide', formatter: function (value, row, index) {
                    if (row.twoLevelType) {
                        return row.twoLevelType.name;
                    } else {
                        return "";
                    }
                }},
                {title: '<b>材质</b>', field: 'material', align: 'center', width: 150, sort: 'clientSide'},
                {title: '<b>规格</b>', field: 'specifications', align: 'center', width: 150, sort: 'clientSide'},
                {title: '<b>包装</b>', field: 'packaging', align: 'center', width: 150, sort: 'clientSide'},
                {title: '<b>日期</b>', field: 'createDate', align: 'center', width: 150, sort: 'clientSide'}
            ]
        ]
    });

    $("#queryProductBtn").click(function () {
        $('#productGrid').datagrid('load', {
            search_LIKE_name: $("#search_LIKE_name").textbox("getValue"),
            "search_EQ_brand.id": $("#search_EQ_brand_id").combobox("getValue"),
            "search_EQ_twoLevelType.id": $("#search_EQ_twoLevelType_id").combobox("getValue"),
            search_GTE_price: $("#search_GTE_price").numberbox("getValue"),
            search_LTE_price: $("#search_LTE_price").numberbox("getValue"),
            search_LIKE_material: $("#search_LIKE_material").textbox("getValue"),
            search_LIKE_specifications: $("#search_LIKE_specifications").textbox("getValue"),
            search_LIKE_packaging: $("#search_LIKE_packaging").textbox("getValue"),
            search_GTE_createDate: $("#search_GTE_createDate").datebox("getValue"),
            search_LTE_createDate: $("#search_LTE_createDate").datebox("getValue")
        });
    });

    $('#brandId').combobox({
        url: 'findAllBrand.json',
        editable: false,
        panelHeight: 'auto',
        valueField:'id',
        textField:'name',
        prompt: "请选择"
    });

    $('#oneLevelTypeId').combobox({
        url: 'findAllOneLevelType.json',
        editable: false,
        panelHeight: 'auto',
        valueField:'id',
        textField:'name',
        prompt: "请选择",
        onChange: function(newValue,oldValue){
            $('#twoLevelTypeId').combobox({
                url: 'findTwoLevelTypeByOneLevelTypeId.json?oneLevelTypeId=' + newValue,
                editable: false,
                panelHeight: 'auto',
                valueField:'id',
                textField:'name',
                prompt: "请选择"
            });
        }
    });

    $("#addProduct").click(function () {
        $('#dlg').dialog({
            title: '新增产品',
            modal: true
        });
        $('#dlg').dialog('open').dialog('center');
        $('#fm').form('clear');
        url = 'saveProduct.json';
    });

    $("#editProduct").click(function(){
        var rows = $('#productGrid').datagrid('getSelections');
        if (rows && rows.length == 1) {
            $('#fm').form('clear');
            $("#id").val(rows[0].id);
            $.get("findProductById.json?id=" + rows[0].id, function (data) {
                if(data){
                    $('#dlg').dialog('open').dialog('center').dialog('setTitle', '修改产品');
                    $('#fm').form('load', data);
                    if(data.brand && data.brand.id) {
                        $('#brandId').combobox("setValue",data.brand.id);
                    }
                    if(data.twoLevelType && data.twoLevelType.id) {
                        $('#oneLevelTypeId').combobox("setValue",data.twoLevelType.oneLevelTypeId);
                        $('#twoLevelTypeId').combobox("setValue",data.twoLevelType.id);
                    }
                }
            });
            url = 'updateProduct.json';
        } else {
            EGIFT_APP.showEditWarnFunc();
        }
    });

    $("#submitProductBtn").click(function(){
        $('#fm').form('submit', {
            url: url,
            onSubmit: function () {
                var result = $(this).form('validate');
                if(result) {
                    $('#dlg').dialog('close');
                }
                return result;
            },
            success: function (data) {
                var obj = JSON.parse(data);
                if (obj.result) {
                    $.messager.show({
                        title: '成功',
                        msg: obj.msg
                    });
                } else {
                    $.messager.show({
                        title: '失败',
                        msg: obj.msg
                    });
                }
                $('#productGrid').datagrid('reload');
            }
        });
    });

    $("#deleteProduct").click(function(){
        var rows = $('#productGrid').datagrid('getSelections');
        if (rows && rows.length > 0) {
            $.messager.confirm('确认', '确认要删除吗？', function (r) {
                if (r) {
                    $.post('deleteProduct.json', {id: rows[0].id}, function (result) {
                        if (result == "success") {
                            $.messager.show({
                                title: '成功',
                                msg: "删除产品成功"
                            });
                            $('#productGrid').datagrid('reload');    // reload the user data
                        } else {
                            $.messager.show({
                                title: '失败',
                                msg: "删除产品失败"
                            });
                        }
                    });
                }
            });
        } else {
            EGIFT_APP.showDeleteWarnFunc();
        }
    });


    $("#managerImage").click(function(){
        var rows = $('#productGrid').datagrid('getSelections');
        if (rows && rows.length > 0) {
            $("#productId").val(rows[0].id);
            $('#addImageDialog').dialog({
                title: '管理产品图片',
                modal: true
            });
            $('#addImageDialog').dialog('open').dialog('center');
            $('#binded_image_grid').datagrid({
                url: 'findProductImageByProductId.json?productId=' + $("#productId").val(),
                singleSelect: true,
                checkOnSelect: false,
                selectOnCheck: false,
                fitColumns: true,
                pagination: false,
                striped: true,
                rownumbers: true,
                columns: [
                    [
                        {field: 'ck', checkbox: true},
                        {title: '<b>图片名称</b>', field: 'fileName', align: 'center', width: 100, sort: 'clientSide'},
                        {title: '<b>图片文件</b>', field: 'url', align: 'center', width: 150, sort: 'clientSide',  formatter: function(value,row,index){
                            if (value){
                                return '<a href="#" onClick="viewImage(' + index + ',event)">' + '查看图片' + '</a>';
                            } else {
                                return value;
                            }
                        }}
                    ]
                ]
            });

        } else {
            EGIFT_APP.showTip("请选择一条产品信息");
            return false;
        }
    });

    $("#addProductImage").click(function(){
        var rows = $('#productGrid').datagrid('getSelections');
        if (rows && rows.length > 0) {
            $("#productId").val(rows[0].id);
            $('#imageFm').form('clear');
            $('#upload_image_dlg').dialog({
                title: '管理产品图片',
                modal: true
            });
            $('#upload_image_dlg').dialog('open').dialog('center');
        } else {
            EGIFT_APP.showTip("请选择一条产品信息");
            return false;
        }
    });

    $("#deleteProductImage").click(function () {
        var selections = $('#binded_image_grid').datagrid('getChecked');
        if (selections.length == 0) {
            EGIFT_APP.showTip("请选择图片");
            return false;
        }
        $.messager.confirm('确认删除图片', '你确定要执行该操作吗？', function (r) {
            if (r) {
                var imagesIds = EGIFT_APP.convertIds2Str(selections);
                if (imagesIds) {
                    $.post("deleteImagesByIds.json", {ids: imagesIds}, function (obj) {
                        if (obj.result) {
                            $.messager.show({
                                title: '成功',
                                msg: obj.msg
                            });
                        } else {
                            $.messager.show({
                                title: '失败',
                                msg: obj.msg
                            });
                        }
                        $('#binded_image_grid').datagrid('reload');
                    })
                } else {
                    EGIFT_APP.showTip("请选择图片");
                }
            }
        });
    });

    Dropzone.options.myAwesomeDropzone = {
        autoProcessQueue: false,
        uploadMultiple: true,
        parallelUploads: 100,
        maxFiles: 100,
        paramName: "uploadfile",
        dictDefaultMessage:"拖拽文件上传到这里，上传",
        acceptedFiles:"image/*",
        addRemoveLinks: true,
        // Dropzone settings
        init: function () {
            var myDropzone = this;
            this.element.querySelector("button[type=submit]").addEventListener("click", function (e) {
                e.preventDefault();
                e.stopPropagation();
                myDropzone.processQueue();
            });
            this.on("sendingmultiple", function () {
            });
            this.on("successmultiple", function (files, response) {
                myDropzone.removeAllFiles();
                if (response.result) {
                    $.messager.show({
                        title: '成功',
                        msg: response.msg
                    });
                } else {
                    $.messager.show({
                        title: '失败',
                        msg: response.msg
                    });
                }
                $('#upload_image_dlg').dialog('close');
                $('#binded_image_grid').datagrid('reload');
            });
            this.on("errormultiple", function (files, response) {
                if (response.result) {
                    $.messager.show({
                        title: '成功',
                        msg: response.msg
                    });
                } else {
                    $.messager.show({
                        title: '失败',
                        msg: response.msg
                    });
                }
                $('#upload_image_dlg').dialog('close');
            });
        }
    }
})

function viewImage(index, e) {
    var data = $("#binded_image_grid").datagrid("getData").rows[index];
    var url = data.url;
    $("#perw").attr("src", url);
    $("#previewDialog").dialog({
        width:600,
        height:450,
        title:"预览图片",
        modal:true
    })
    $("#previewDialog").dialog('open').dialog('center');
    if (e && e.stopPropagation) {
        //因此它支持W3C的stopPropagation()方法
        e.stopPropagation();
    } else {//否则，我们需要使用IE的方式来取消事件冒泡
        window.event.cancelBubble = true;
    }
};
